package com.sanwei.taskmanagement.controller;

import com.sanwei.taskmanagement.model.User;
import com.sanwei.taskmanagement.model.dto.UserDto;
import com.sanwei.taskmanagement.service.AuthService;
import com.sanwei.taskmanagement.service.impl.AuthServiceImpl;
import com.sanwei.taskmanagement.service.impl.UserServiceImpl;
import com.sanwei.taskmanagement.util.JwtUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private AuthServiceImpl authService;

    @Resource
    private UserServiceImpl userService;

    @PostMapping("/login")
    public String login(String username,String password) {
        if (username.isEmpty()) {
            throw new RuntimeException("username is null");
        }
        if (password.isEmpty()) {
            throw new RuntimeException("password is null");
        }
        if (authService.login(username,password)) {
            // 生成jwt
            String token = JwtUtil.generateToken(username);
            System.out.println("token: " + token);
            return "登录成功\n" + token;
        }
        return "登录失败";
    }

    @PostMapping("/register")
    public String register(@RequestBody UserDto userDto) {
        User user = new User();
        user.setUsername(userDto.getUsername());
        user.setPassword(userDto.getPassword());
        if (authService.register(user)) {
            return "注册成功";
        }
        return "注册失败";
    }
}
